import { ref,computed } from 'vue'
import { defineStore } from 'pinia'
import {getCategoryListAPI} from '@/API/goods'

import {useUserStore} from '@/stores/user'


export const useGoodsStore = defineStore('goods', () => {
  const goodsList = ref<any[]>([])
  const userStore = useUserStore()
 

  //合并本地购物车
  const getGoodsList =async ()=>{
   const res=await getCategoryListAPI(goodsList.value)
   console.log(res);
   
  
  }


  //加入购物车
  const addGoodsList =async (goods:any) =>{
    
    
    const item:any=goodsList.value.find((item:any) => item.id===goods.id)
    if(item){
      item.amount++
    }else{
      goodsList.value.push(goods)
    }
  
   
  }

  //删除购物车数据

  const delGoodsList =async(id:any)=>{
    
    
    goodsList.value= goodsList.value.filter(item=>item.id!==id)

   
   
   
    
  }
   
   //更新购物车数量




   
  //总金额
  
  const total=computed(()=>goodsList.value.filter(item=>item.checked).reduce((sum,item)=>sum+item.amount*item.price,0))
    // if(goodsList.value){
     
    // }
  
  
  //计算是否全选
  const all = computed(()=>goodsList.value.every(item=>item.checked));
  
 
    
  //计算所有选中商品的数量
    
  const checkedNum=computed(()=>goodsList.value.filter(item=>item.checked).reduce((sum,item)=>sum+=item.amount,0))   
  
  //点击全选改变所有状态
  const isChangeAll = async(checked:any)=>{
   
    goodsList.value.forEach(item=>item.checked=checked)
  }

  


  return {
    goodsList,
    addGoodsList,
    delGoodsList,
    total,
    all,
    checkedNum,
    isChangeAll,
    getGoodsList,
    
    
   }
   
},
{
  persist: true,
}
)
